
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Router } from 'vue-router'

export const useAuthModalStore = defineStore('authModal', () => {
    const visible = ref(false)
    const countdown = ref(5)
    const targetPath = ref('')
    let timer: number | null = null
    let router: Router | null = null // 路由实例

    // 设置路由实例的方法
    const setRouter = (r: Router) => {
        router = r
    }

    const resetModal = () => {
        visible.value = false
        countdown.value = 5
        if (timer) {
            clearInterval(timer)
            timer = null
        }
    }

    const navigateToLogin = () => {
        if (!router) {
            console.error('路由实例未初始化')
            return
        }

        resetModal()
        router.push('/Login?redirect=' + encodeURIComponent(targetPath.value))
    }

    const showModal = (path: string) => {
        resetModal()
        targetPath.value = path
        visible.value = true

        timer = window.setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                navigateToLogin()
            }
        }, 1000)
    }

    return {
        visible,
        countdown,
        targetPath,
        showModal,
        navigateToLogin,
        resetModal,
        setRouter
    }
})